package class1.s2022350143027.service.Impl;

import class1.s2022350143027.data.GoodsData;
import class1.s2022350143027.model.GoodsModel;
import class1.s2022350143027.service.YzyGoodsService;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.*;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.mysql.jdbc.jdbc2.optional.*;

import javax.sql.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.*;

/**
 * 库存管理业务逻辑实现
 *
 * @author yzy
 * @date 2024-05-02
 */
public class YzyGoodsServiceImpl implements YzyGoodsService {
    protected GoodsData goodsData = new GoodsData();

    public GoodsData getGoodsData() {
        return goodsData;
    }


    public void find_goods(String lookGood_name) {
        System.out.println("=======================商品信息===========================");
        System.out.println("===  ==编号==    ==名称==      ==单价==    ==库存数量==  ===");
        Pattern pattern = Pattern.compile(lookGood_name, Pattern.CASE_INSENSITIVE);
        for (GoodsModel goodsBaseModel : goodsData.getGoodsDataList()) {
            Matcher matcher = pattern.matcher(goodsBaseModel.getGoodName());
            if (matcher.find()) {
                //把找到的商品输出
                System.out.printf("===    " + "%-10s %-11s %-11d %-10d===", goodsBaseModel.getGoodId(), goodsBaseModel.getGoodName(), goodsBaseModel.getGoodPrice(), goodsBaseModel.getGoodNumber());
                System.out.println(" ");
            }
        }
    }


    public boolean save(GoodsModel goodsBaseModel) {
        goodsData.getGoodsDataList().add(goodsBaseModel);
        return true;
    }


    // 保存数据到 YzyGoodData.txt
    public boolean SaveDataToTxt() {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter("YzyGoodData.txt"))) {
            // 写入表头
            writer.write("=======================商品信息===========================");
            writer.write("\n");
            String header = String.format("%-15s%-15s%-15s%-15s", "商品ID", "商品名字", "商品价格", "商品数量");
            writer.write(header);
            writer.newLine();

            // 写入数据
            for (GoodsModel model : goodsData.getGoodsDataList()) {
                String line = String.format("%-21s%-21s%-21d%-21d", model.getGoodId(), model.getGoodName(),
                        model.getGoodPrice(), model.getGoodNumber());
                writer.write(line);
                writer.newLine();
            }
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }


    public void update(String goodId, int number_choice) {
        Iterator<GoodsModel> it_n = goodsData.getGoodsDataList().iterator();
        GoodsModel obj_n;
        while (it_n.hasNext()) {
            obj_n = it_n.next();
            if (obj_n.getGoodId().equals(goodId)) {

                if (number_choice < 0) {
                    obj_n.setGoodNumber(obj_n.getGoodNumber() - Math.abs(number_choice));
                }
                if (number_choice >= 0) {
                    obj_n.setGoodNumber(obj_n.getGoodNumber() + number_choice);
                }

                System.out.println("=======================商品信息===========================");
                System.out.println("===  ==编号==    ==名称==      ==单价==    ==库存数量==  ===");
                System.out.printf("===    " + "%-10s %-11s %-11d %-10d===", obj_n.getGoodId(), obj_n.getGoodName(), obj_n.getGoodPrice(), obj_n.getGoodNumber());
                System.out.println(" ");
                return;
            }
        }
        System.out.println("未找到该商品！");
    }


    //删除逻辑要嵌套sql查找删除
    public boolean delete(String lookGood_id) throws SQLException {
        Iterator<GoodsModel> it_d = goodsData.getGoodsDataList().iterator();
        GoodsModel obj_d;
        while (it_d.hasNext()) {
            obj_d = it_d.next();
            if (obj_d.getGoodId().equals(lookGood_id)) {
                goodsData.getGoodsDataList().remove(obj_d);
                //调用sql删除逻辑
                DeleteDataFromSql(obj_d);
                return true;
            }
        }
        return false;
    }

    //临时表中的删除时调用此函数进行SQL删除
    public boolean DeleteDataFromSql(GoodsModel model) throws SQLException {

        String id = model.getGoodId();
        String name = model.getGoodName();
        int price = model.getGoodPrice();
        int num = model.getGoodNumber();

        //1.创建"数据源"
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource) dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/yzy1?characterEncoding=utf8&useSSL=false");
        //设置用户
        ((MysqlDataSource) dataSource).setUser("root");
        //设置密码
        ((MysqlDataSource) dataSource).setPassword("yzy824ap0stol");


        //2.跟数据库服务器建立连接
        Connection connection = dataSource.getConnection();

        //3.SQL语句构造
        String sql = "delete from student where id = ?";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setString(1, id);

        //4.执行sql语句
        int n = statement.executeUpdate(); //返回值为这次操作影响了几行

        if (n > 0) {
            System.out.println("删除成功");
            System.out.println("一共影响了: " + n + "行");
        } else {
            System.out.println("未找到您要删除的对象");
        }


        //5.释放必要资源
        statement.close();
        connection.close();

        return true;
    }

    public void show() {
        System.out.println("=======================商品信息===========================");
        System.out.println("===  ==编号==    ==名称==      ==单价==    ==库存数量==  ===");

        Iterator<GoodsModel> it_g = goodsData.getGoodsDataList().iterator();
        GoodsModel obj_g;
        while (it_g.hasNext()) {
            obj_g = it_g.next();
            System.out.printf("===    " + "%-10s %-11s %-11d %-10d===", obj_g.getGoodId(), obj_g.getGoodName(), obj_g.getGoodPrice(), obj_g.getGoodNumber());
            System.out.println(" ");
        }
    }


    public boolean SaveDataToSql() {

        try (BufferedWriter writer = new BufferedWriter(new FileWriter("YzyGoodData.txt"))) {

            // 写入数据
            for (GoodsModel model : goodsData.getGoodsDataList()) {
                String id = model.getGoodId();
                String name = model.getGoodName();
                int price = model.getGoodPrice();
                int num = model.getGoodNumber();


                //1.创建"数据源"
                DataSource dataSource = new MysqlDataSource();
                ((MysqlDataSource) dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/yzy1?characterEncoding=utf8&useSSL=false");
                //设置用户
                ((MysqlDataSource) dataSource).setUser("root");
                //设置密码
                ((MysqlDataSource) dataSource).setPassword("yzy824ap0stol");


                //2.跟数据库服务器建立连接
                Connection connection = dataSource.getConnection();


                //3.SQL语句构造
                //String sql = "insert into student values("+ id +",' "+ name +" ')";
                String sql = "insert into yzygoods values(?,?,?,?)";
                PreparedStatement statement = connection.prepareStatement(sql);
                statement.setString(1, id);
                statement.setString(2, name);
                statement.setInt(3, price);
                statement.setInt(4, num);


                //4.执行sql语句
                int n = statement.executeUpdate(); //返回值为这次操作影响了几行

                System.out.println("sql一共影响了: " + n + "行");


                //5.释放必要资源
                statement.close();
                connection.close();

            }
            return true;
        } catch (IOException | SQLException e) {
            e.printStackTrace();
            return false;
        }

    }


    public boolean LoadDataFromSql() throws SQLException {

        //1.创建"数据源"
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource) dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/yzy1?characterEncoding=utf8&useSSL=false");
        //设置用户
        ((MysqlDataSource) dataSource).setUser("root");
        //设置密码
        ((MysqlDataSource) dataSource).setPassword("yzy824ap0stol");


        //2.跟数据库服务器建立连接
        Connection connection= dataSource.getConnection();


        //3.SQL语句构造
        String sql = "select * from yzygoods";
        PreparedStatement statement= connection.prepareStatement(sql);

        //4.执行查询操作
        //返回值是一个ResultSet对象,表示一个表格
        ResultSet resultSet = statement.executeQuery(); //返回值为这次操作影响了几行

        //遍历,以行位访问
        //next会先指向第一个元素之前,每次调用next,往下走一步,查看是否有可用元素,有的话返回true,从而进入循环,否则返回false,退出循环
        //在循环中就可以取出这一行的每一列
        //当执行完最后一行,再执行next,就会返回false
        int cnt=0;
        while(resultSet.next())
        {
            String id = resultSet.getString("id");
            String name = resultSet.getString("name");
            int price = resultSet.getInt("price");
            int num = resultSet.getInt("amount");

            GoodsModel goodsBaseModel= new GoodsModel(id,name,price,num);
            goodsData.getGoodsDataList().add(goodsBaseModel);
            cnt++;
            System.out.println("载入"+cnt+"条");
        }


        //5.释放必要资源
        statement.close();
        connection.close();
        resultSet.close(); //只要是对象都要关闭

        return true;

    };


}
